import sqlLite from '../../common/sqllite-utils';

/**
 * 当点击确定入库按钮所触发逻辑
 */
export function confirmInventory() {
  this.$refs.uForm.validate((valid) => {
  		if (valid) {
      const data = {
        hb_rock_ku_shi_id: uni.getStorageSync('shiyouid'),
        hb_rock_zhuangxh_id: this.nameid,
        lai_yuan_id: this.sourceval,
        rfid: this.RFID,
        depid: this.deptnameVal,
        shelves_id: this.shelfCode,
        allotmentTime: this.allotVal,
        over_time: this.overdueAllotVal ? this.overdueAllotVal : ' ',
      };
      if (!uni.getStorageSync('shiyouid')) {
        this.$refs.uToast.show({
          title: '请先选择相应的库室！',
          type: 'warning',
        });
        return false;
      }
      // 首先查找当前插入数据，用此时的rfid去比对表中的数据，若有重复，则提示rfid重复，终止插入操作
      const tableName = 'equipmentStorageTables';
      sqlLite.selectFromTable(
           	`select * from ${tableName}`,
      ).then((res) => {
        if (res.length > 0) {
          for (let i = 0; i < res.length; i++) {
            if (this.RFID == res[i].rfid) {
              this.$refs.uToast.show({
                title: 'RFID重复！',
                type: 'warning',
              });
              return false;
            }
          }

          // 当循环后没有返回，此时可以插入新的数据
          sqlLite.executeSqlCode(
             	`insert into equipmentStorageTables (hb_rock_ku_shi_id,hb_rock_zhuangxh_id,lai_yuan_id,rfid,depid,shelves_id,allotmentTime,over_time) values ("${data.hb_rock_ku_shi_id}","${data.hb_rock_zhuangxh_id}","${data.lai_yuan_id}","${data.rfid}","${data.depid}","${data.shelves_id}","${data.allotmentTime}","${data.over_time}")`,
          ).then((res) => {
            if (JSON.stringify(res) === '{}') {
              this.$refs.uToast.show({
                title: '插入数据成功！',
                type: 'success',
              });
            }
          }).catch((err) => {
          });
        } else {
          // 当不大于0的时候，此时无数据，咋插入该数据项
          sqlLite.executeSqlCode(
             	`insert into equipmentStorageTables (hb_rock_ku_shi_id,hb_rock_zhuangxh_id,lai_yuan_id,rfid,depid,shelves_id,allotmentTime,over_time) values ("${data.hb_rock_ku_shi_id}","${data.hb_rock_zhuangxh_id}","${data.lai_yuan_id}","${data.rfid}","${data.depid}","${data.shelves_id}","${data.allotmentTime}","${data.over_time}")`,
          ).then((res) => {
            if (JSON.stringify(res) === '{}') {
              this.$refs.uToast.show({
                title: '插入数据成功！',
                type: 'success',
              });
            }
          }).catch((err) => {
          });
        }
      });
  		}
  	});
}
